/**
 * Created by 小敏哥 on 2018/1/4.
 */
import React, {Component} from 'react';
import {connect} from 'react-redux';
import {Toast} from 'antd-mobile';
import ItemList from '../../../../../../../src/js/components/itemList';
import ReModal from '../../../../../../../src/js/components/reModal';
import ProvinceInputItem from '../../../../../../../src/js/components/provinceInputItem';
import InputWithDelete from '../../../../../../../src/js/components/inputWithDelete';
import {getAddCarRule, addCar} from '../../actions/addCarAction'
import style from './index.scss';
import common from "../../../../../../js/utils/common";

class AddCar extends Component {
    constructor(props) {
        super(props);
        this.state = {
            isChecked: false,
            CarEngineLen: 0,//是否显示引擎号输入框相关配置
            CarCodeLen: 0,//是否显示车身架号输入框相关配置
            provinces: [],
        };
        //缓存用户输入数字
        this.data = {
            carNumber: {
                check: false,
                value: '',
                msg: '请输入正确的车牌号码',
                shouleCheck: true,//是否需要检查
            },
            carEngine: {
                check: false,
                value: '',
                msg: '请输入正确的发动机号',
                shouleCheck: true,//是否需要检查
            },
            carCode: {
                check: false,
                value: '',
                msg: '请输入正确的车身架号',
                shouleCheck: true,//是否需要检查
            },
            phone: {
                check: false,
                value: '',
                msg: '请输入正确的手机号码',
                shouleCheck: true,//是否需要检查
            }
        }

    }

    //设置输入框的值
    setValue(valueType, value, check) {
        this.data[valueType].value = value;
        this.data[valueType].check = check;
    }

    //检查所有数据
    checkAllData() {
        for (let index in this.data) {
            if (this.data[index].shouleCheck && !this.data[index].check) {
                Toast.info(this.data[index].msg, 2);
                return false;
            }
        }
        return true;
    }

    componentDidMount() {
        common.setViewTitle('添加车辆');
        //无缓存时重新请求数据
        if (this.props.addCarRule) {
            let resultObj = JSON.parse(this.props.addCarRule);
            this.getCarProvince(resultObj);
        }
        else {
            this.props.dispatch(getAddCarRule({}, (result) => {
                let resultObj = JSON.parse(result);
                this.getCarProvince(resultObj);
            }));
        }
    }

    getCarProvince(result) {
        let provinceArray = [];
        for (let provinceItem of result) {
            provinceArray.push(provinceItem.ProvincePrefix);
        }
        this.setState({
            provinces: provinceArray
        });
    }

    //根据获得的配置数据和输入的车牌，配置不同的显示项
    changeInputStatus(value) {
        if (value.length >= 2) {
            let find = false;
            let allConfig = JSON.parse(this.props.addCarRule);
            let prefix = value.substr(0, 1);
            let prefixWithCity = value.substr(0, 2);
            for (let provinceItem of allConfig) {
                if (find) {
                    break;
                }
                if (prefix == provinceItem.ProvincePrefix) {
                    for (let cityItem of provinceItem.Cities) {
                        //直辖市仅校验第一位
                        if (cityItem.CarNumberPrefix == prefixWithCity || ((prefix == '京' || prefix == '津' || prefix == '沪' || prefix == '渝') && cityItem.CarNumberPrefix == prefix)) {
                            this.setState({
                                CarEngineLen: cityItem.CarEngineLen,//是否显示引擎号输入框相关配置
                                CarCodeLen: cityItem.CarCodeLen,//是否显示车身架号输入框相关配置
                            });
                            //0时无需显示，直接讲检查状态设置为正确
                            if (cityItem.CarEngineLen == 0) {
                                this.data.carEngine.shouleCheck = false;
                            }
                            else {
                                this.data.carEngine.shouleCheck = true;
                            }
                            if (cityItem.CarCodeLen == 0) {
                                this.data.carCode.shouleCheck = false;
                            }
                            else {
                                this.data.carCode.shouleCheck = true;
                            }

                            find = true;
                            break;
                        }
                    }
                }
            }
            if (!find) {
                this.setState({
                    CarEngineLen: 0,//是否显示引擎号输入框相关配置
                    CarCodeLen: 0,//是否显示车身架号输入框相关配置
                });
                this.data.carCode.shouleCheck = false;
                this.data.carEngine.shouleCheck = false;
            }
        }
        else {
            this.setState({
                CarEngineLen: 0,//是否显示引擎号输入框相关配置
                CarCodeLen: 0,//是否显示车身架号输入框相关配置
            });
        }
    }

    //设置是否开通消息通知
    setMessageCheckStatus() {
        this.setState({
            isChecked: !this.state.isChecked,
        }, () => {
            if (this.state.isChecked) {
                this.data.phone.shouleCheck = true;
            }
            else {
                this.data.phone.shouleCheck = false;
            }
        })
    }

    submit() {
        setTimeout(() => {
            if (this.checkAllData()) {
                let data = {
                    carCode: this.data.carCode.value,
                    carNumber: this.data.carNumber.value,
                    engineNumber: this.data.carEngine.value,
                    phone: this.data.phone.value,
                    isSubscribe: this.state.isChecked ? '1' : '0'
                };
                this.props.dispatch(addCar(data, (result) => {
                    Toast.info('添加车辆成功', 2)
                    setTimeout(() => {
                        history.back();
                    }, 2000);
                    //console.log(result);
                }))
            }
        }, 0);
    }

    //发动机小图标点击
    carEngineIconClick() {
        ReModal.showOnlyComponent(<img className={style.alertImg} src="./images/EngineImgB.png" onClick={() => {
            ReModal.close();
        }}/>)
    }

    //车身架号小图标点击
    carCodeIconClick() {
        ReModal.showOnlyComponent(<img className={style.alertImg} src="./images/EngineImgA.png" onClick={() => {
            ReModal.close();
        }}/>)
    }

    //发动机号变成大写
    valueToUpper(value) {
        return value.toUpperCase();
    }

    render() {
        return <div className={style.carDetail}>
            <div className={style.headerTips}>所填信息为当地交管局查询所需，您的信息将严格保密</div>
            <ItemList borderPaddingLeft="0.3rem">
                <ProvinceInputItem title="车牌号码" areaList={this.state.provinces} onChange={(result, check) => {
                    this.changeInputStatus(result);
                    this.setValue('carNumber', result, check);
                }} onInput={(value) => {
                    this.changeInputStatus(value)
                }}/>
                {this.state.CarEngineLen > 0 ? <InputWithDelete icon="./images/about.png" title="发动机号"
                                                                placeholder={this.state.CarEngineLen == 99 ? "请输入完整发动机号" : `请输入发动机号后${this.state.CarEngineLen}位`}
                                                                regular={this.state.CarEngineLen == 99 ? "^[A-Za-z0-9]+$" : `^[A-Za-z0-9]{${this.state.CarEngineLen}}$`}
                                                                maxLength={this.state.CarEngineLen == 99 ? undefined : this.state.CarEngineLen}
                                                                changeValue={(value) => {
                                                                    return this.valueToUpper(value)
                                                                }}
                                                                errorCallBack={(value) => {
                                                                    this.setValue('carEngine', value, false);
                                                                }} currentCallBack={(value) => {
                    this.setValue('carEngine', value, true);
                }} iconClick={this.carEngineIconClick.bind(this)}/> : ''}
                {this.state.CarCodeLen > 0 ? <InputWithDelete icon="./images/about.png" title="车身架号"
                                                              placeholder={this.state.CarCodeLen == 99 ? "请输入完整车身架号" : `请输入车身架号后${this.state.CarCodeLen}位`}
                                                              regular={this.state.CarCodeLen == 99 ? "^[A-Za-z0-9]+$" : `^[A-Za-z0-9]{${this.state.CarCodeLen}}$`}
                                                              maxLength={this.state.CarCodeLen == 99 ? undefined : this.state.CarCodeLen}
                                                              changeValue={(value) => {
                                                                  return this.valueToUpper(value)
                                                              }}
                                                              errorCallBack={(value) => {
                                                                  this.setValue('carCode', value, false);
                                                              }} currentCallBack={(value) => {
                    this.setValue('carCode', value, true);
                }} iconClick={this.carCodeIconClick.bind(this)}/> : ''}
                <InputWithDelete title="手机号码" placeholder="请输入手机号码" regular="^1\d{10}$" maxLength={11}
                                 errorCallBack={(value) => {
                                     this.setValue('phone', value, false);
                                 }} currentCallBack={(value) => {
                    this.setValue('phone', value, true);
                }}/>
            </ItemList>
            {/*   <div className={style.userMessage}>
                <ItemList borderPaddingLeft="0.3rem">
                    <div className={style.newMessageStatus}>
                        <div>开通新违章消息通知服务</div>
                        <Switch disabled={false} onChange={() => {
                            this.setMessageCheckStatus()
                        }} checked={this.state.isChecked}/>
                    </div>
                    {this.state.isChecked ?
                        <InputWithDelete placeholder="请输入手机号码" errorCallBack={(value) => {
                            this.setValue('phone', value, false);
                        }} currentCallBack={(value) => {
                            this.setValue('phone', value, true);
                        }}/> : ''}
                </ItemList>
            </div>*/}
            <div className={style.headerTips}>
                2-5个工作日内将办理结果发送到您的手机上，请准确填写
            </div>

            <button className={style.save} onClick={() => {
                this.submit()
            }}>保存信息
            </button>
            <img className={style.bottomImg} src="./images/index-bottom.png"/>
        </div>
    }
}

function mapStateToProps(state) {
    return Object.assign({}, state.addCarInfo);
}

export default connect(mapStateToProps)(AddCar);